package com.cyk.demo2.base
import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.core.MethodParameter
import org.springframework.http.MediaType
import org.springframework.http.converter.HttpMessageConverter
import org.springframework.http.server.ServerHttpRequest
import org.springframework.http.server.ServerHttpResponse
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice
import javax.annotation.Resource

/**
 * 实现统一数据返回的保底类
 * 说明：在返回数据之前，检测数据类型是否为统一对象，如果不是就封装
 */
@ControllerAdvice
class BaseRespHandler : ResponseBodyAdvice<Any?> {

    @Resource
    private lateinit var objectMapper: ObjectMapper

    /**
     * 开关
     */
    override fun supports(returnType: MethodParameter, converterType: Class<out HttpMessageConverter<*>>): Boolean {
        return true
    }

    /**
     * 对数据格式进行校验和封装
     */
    override fun beforeBodyWrite(
        body: Any?,
        returnType: MethodParameter,
        selectedContentType: MediaType,
        selectedConverterType: Class<out HttpMessageConverter<*>>,
        request: ServerHttpRequest,
        response: ServerHttpResponse
    ): Any? {
        if (body is ApiResp<*>) {
            return body
        }
        // String比较特殊，要单独处理
        if (body is String) {
            return objectMapper.writeValueAsString(ApiResp.ok(body))
        }
        return ApiResp.ok(body)
    }

}
